package aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import pojo.MyUser;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component
@Aspect
public class MD5Aspect {

    private MessageDigest digest;

    public MD5Aspect(){
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    @Around(value = "execution(* service.MyUserService.add(pojo.MyUser))")
    public Object registerAround(ProceedingJoinPoint point){
        Object o = null;
        MyUser myUser = (MyUser) point.getArgs()[0];
        try {
            myUser.setPsd(process(myUser.getPsd()));
            o = point.proceed(new Object[]{myUser});
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return o;
    }

    @Around(value = "execution(* service.MyUserService.login(pojo.MyUser))")
    public Object loginAround(ProceedingJoinPoint point){
        Object o = null;
        MyUser myUser = (MyUser) point.getArgs()[0];
        try {
            myUser.setPsd(process(myUser.getPsd()));
            o = point.proceed(new Object[]{myUser});
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return o;
    }

    private String process(String s){
        String ss=null;
        try {
            byte[] bs=digest.digest(s.getBytes("ISO-8859-1"));
            ss=new BigInteger(1, digest.digest(s.getBytes())).toString(16);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return ss;
    }


}
